package mx.com.sinformex.simbel.utils.export;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.services.Response;

import mx.com.sinformex.simbel.utils.IFileReporteExporter;

/**
 * @author Oscar Ivan Hernandez Ventura [ oscar at sinformex dot com dot mx]
 *
 * @version $ Id : CsvExporter.java , v 1.0 14/05/2009 angellore $
 */
public class CsvExporter implements IFileReporteExporter {

	public StreamResponse export(List<Map<String, Object>> rows, String templateFileName,Map<String, Object> parameters, java.sql.Connection conn, String outputFilename) {
		StringBuilder builder = new StringBuilder();
		boolean header= false;
		
		for(Map<String, Object> row : rows) {
			
			if(!header) {
				for(Iterator<String> iter = row.keySet().iterator() ; iter.hasNext() ; ) {
					builder.append(String.format("%s,",iter.next()));
				}
				builder.append("\n");
				header = true;
			}
			
			for(Iterator<String> iter = row.keySet().iterator() ; iter.hasNext() ; ) {
				String key = iter.next();
				builder.append(String.format("%s,",row.get(key)));
			}
			
			builder.append("\n");
		}
		return new CsvStreamResponse(builder.toString(), outputFilename);
	}
	
	class CsvStreamResponse implements StreamResponse {

		private final String CONTENT_TYPE = "application/vnd.ms-excel";
		private InputStream in;
		private String filename ;
		private final String EXTENSION = ".csv";
		
		@SuppressWarnings("deprecation")
		public CsvStreamResponse(String string, String filename) {
			in = new StringBufferInputStream(string);
			this.filename = filename;
		}
		
		public String getContentType() {
			return CONTENT_TYPE;
		}

		public InputStream getStream() throws IOException {
			return in;
		}

		public void prepareResponse(Response response) {
			response.setHeader("Content-Disposition", "attachment; filename=" + filename + EXTENSION);
			response.setHeader("Expires", "0");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");			
		}
		
	}

}
